#!/usr/bin/env python
import time
import random
from threadpool import ThreadPool, makeRequests

def task(d):
    i = random.randint(1,5)
    print "sleep %d" % i
    time.sleep(i)

def print_result(request, result):
        print "**** Result from request #%s: %r" % (request.requestID, result)


def handle_exception(request, exc_info):
    if not isinstance(exc_info, tuple):
        # Something is seriously wrong...
        print request
        print exc_info
        raise SystemExit
    print "**** Exception occured in request #%s: %s" % \
      (request.requestID, exc_info)


requests = makeRequests(task, [1], print_result, handle_exception)
main = ThreadPool(3)
for req in requests:
    main.putRequest(req)
    print "Work request #%s added." % req.requestID
#main.poll()
#main.wait()
time.sleep(5)
requests = makeRequests(task, [1,2,3,4,5,6,7], print_result, handle_exception)
for req in requests:
    main.putRequest(req)
    print "Work request #%s added." % req.requestID
    
time.sleep(100)
